
<template>
  <div>
    <div class="seach">
      <input type="text" 
             placeholder="请输入城市名或拼音" 
             class="seach-input"
             v-model="keyWord"
      >
    </div>
    <div class="search-content" 
         ref="search"
         v-show="keyWord"
    >
      <ul>
        <li class="search-iteam border-bottom"
            v-for="itea of list" :key="itea.id"
            @click="cityClick(itea.name)"
        >
          {{ itea.name }}
        </li>
        <li class="search-iteam border-bottom"
            v-show="hasNoData"
        >
          未找到匹配项
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll"
import { mapState , mapMutations} from 'vuex'
export default {
  name: "CitySeach",
  props: {
    cities: Object
  },
  data () {
    return {
      keyWord: "",
      list: [],
      timer: 0
    }
  },
  watch: {
    keyWord (val) {
      if (this.timer) { 
        clearTimeout(this.timer)
      }
      if(!this.keyWord) {
        this.list = []
      }
      this.timer = setTimeout(()=>{
        const citys = []
        for(let i in this.cities) {
          this.cities[i].forEach(element => {
            if(element.spell.indexOf(this.keyWord) > -1 ||
               element.name.indexOf(this.keyWord) > -1) {
                 citys.push(element)
               }
          })
        }
        this.list = citys
      },100)
    }
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.search)
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    cityClick(cityName){
      //首先派发操作
      // this.$store.dispatch("cityChange", cityName)
      //数据量比较少，可以跳过数据派发环节直接操作数据
      // this.$store.commit("cityChange", cityName)
      this.cityChange(cityName)
      this.$router.push("/")
    },
    ...mapMutations(['cityChange'])
  }
}
</script>


<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .seach
    padding: 0 .1rem
    height: .72rem 
    background: $bgColor
    .seach-input
      box-sizing: border-box
      padding: 0 .1rem  
      width: 100%
      height: .62rem
      line-height: .62rem
      text-align: center
      border-radius: .06rem
      color: #666

  .search-content
    width: 100% 
    z-index: 1
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    bottom: 0
    background: #eee
    .search-iteam
      display: block
      line-height: .62rem
      padding-left: .2rem
      background: #fff 
      color #666


</style>

